package org.etom.impl.ui.wizards;

import org.eclipse.jface.wizard.Wizard;
import org.eclipse.osgi.util.NLS;
import org.etom.connector.datatypes.IMoodleConnection;
import org.etom.connector.service.ConnectorException;
import org.etom.connector.service.MoodleConnector;
import org.etom.impl.ui.Activator;
import org.etom.impl.ui.util.Logger;

public class NewAccountWizard extends Wizard {

  private IMoodleConnection moodleConnection;//used for edit operation
  private NewAccountWizardPage1 wizardPage;
  private IMoodleConnection connection;
  
  public NewAccountWizard(IMoodleConnection moodleConnection) {
    super();
    this.moodleConnection = moodleConnection;
  }

  /*===[Wizard methods][Start]===*/
  @Override
  public void addPages() {
    if (wizardPage == null) {
      wizardPage = new NewAccountWizardPage1(moodleConnection);
    }
    addPage(wizardPage);
  }

  @Override
  public boolean performFinish() {
    createMoodleConnection();
    return (this.connection != null);
  }
  /*===[Wizard methods][End]===*/

  public IMoodleConnection getMoodleConnection() {
    return this.connection;
  }
  
  private void createMoodleConnection() {
    if (wizardPage == null) return;
    MoodleConnector connector = Activator.getDefault().getMoodleConnector();
    try {
      connection = connector.getConnection(
          wizardPage.getMoodleUrl(),
          wizardPage.getRpcServerUrl(),
          wizardPage.getUsername(),
          wizardPage.getPassword());
      if (wizardPage.validateOnFinish()) {
        try {
          connection.getUser();
        } catch (ConnectorException ce) {
          Logger.ERROR(WizardsMessages.NewAccount_Wizard_Validate_Connection_Fail, ce);
        }
      }
    } catch (ConnectorException ce) {
      wizardPage.setErrorMessage(NLS.bind(
          WizardsMessages.NewAccount_Wizard_Create_Connection_Fail, ce.getMessage()));
    }
  }
  
}
